package d512a.TAKO;

import java.util.Random;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.client.android.CaptureActivity;

import d512a.TAKO.helpers.DataBaseHelper;
import d512a.TAKO.helpers.DateHelper;

public class ProductInfoBasicActivity extends Activity {

	private DataBaseHelper foodDB;
	private TextView txtProductName;
	private TextView txtRatingValue;
	private Button btnPutInBasket;
	private String foodId;
	private String productName;
	private String scanningsID;
	private String recID;
	private final String date = DateHelper.getDate();
	
	private final float SUGAR_LIMIT = 6.0f, FAT_LIMIT = 20.0f, LOWEST_LIMIT = 2.0f, ALCOHOL_LIMIT = 4.0f, CARB_LIMIT = 30.0f, SAT_FAT_LIMIT = 5.0f;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_info_basic);

		handleDatabase();
		addWidgetReferences();
		setWidgetListeners();
		foodId = getIntent().getExtras().getString("foodId");
		scanningsID = getIntent().getExtras().getString("scanningsID");
		recID = getIntent().getExtras().getString("rec_id");
		
		productName = getProductName(foodId);
		getRatingValue(foodId);
		
		if (ProductTabWidgetActivity.fromScan)
			setRecommendationType();
		//seriousRecommender();
		//provocativeRecommender();
		//standardRecommender();
	}

	private void handleDatabase() {
		foodDB = new DataBaseHelper(this);

		try {
			foodDB.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		} finally {
			foodDB.close();
		}
	}

	private void addWidgetReferences() {
		txtProductName = (TextView) findViewById(R.id.txtProductName);
		txtRatingValue = (TextView) findViewById(R.id.txtRatingValue);
		btnPutInBasket = (Button) findViewById(R.id.btnPutInBasket);
		// btnGetBasketTable = (Button) findViewById(R.id.btnGetBasketTable);
		// btnGetRecommendedTable =
		// (Button)findViewById(R.id.btnGetRecommendedTable);
		// txtTableContent = (TextView) findViewById(R.id.txtTableContent);
	}

	private void setWidgetListeners() {
		txtRatingValue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ProductInfoBasicActivity.this,
						RecommenedProductsActivity.class);
				intent.putExtra("foodId", foodId);
				intent.putExtra("scanningsID", scanningsID);
				String date = DateHelper.getDate();
				if (ProductTabWidgetActivity.fromScan == true) {
	                Cursor c = foodDB.insertInRecommended(0, null, scanningsID, 5, date);
	                c.close();
	            } else {
	                // Get lastly inserted _id in the Recommended table
	                Cursor c = foodDB.getRecommendedPrimKey_id();
	                c.moveToFirst();
	                String recommend_idPrimKey = c.getString(0);
	                foodDB.insertInRecommended(0, recommend_idPrimKey, null, 5, date);
	                c.close();
	            }
				startActivity(intent);
			}
		});

		btnPutInBasket.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				putProductInBasket(productName, foodId);
			}
		});
		// btnGetBasketTable.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// txtTableContent.setText("");
		// Cursor cursor = foodDB.getBasketTable();
		// StringBuilder builder = new StringBuilder("Basket Table:\n");
		// if (cursor.getCount() > 0) {
		// while (cursor.moveToNext()) {
		// builder.append(cursor.getString(0)).append("#");
		// builder.append(cursor.getString(1)).append("#");
		// builder.append(cursor.getString(2)).append("#");
		// builder.append(cursor.getString(3)).append("#");
		// builder.append(cursor.getString(4)).append("#");
		// builder.append(cursor.getString(5)).append("#");
		// builder.append(cursor.getString(6)).append("\n");
		// }
		// txtTableContent.setText(builder);
		// cursor.close();
		// }
		// }
		// });
		// btnGetRecommendedTable.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// txtTableContent.setText("");
		// Cursor cursor = foodDB.getRecommendedTable();
		// StringBuilder builder = new StringBuilder("Recommended Table:\n");
		// if (cursor.getCount() > 0) {
		// while (cursor.moveToNext()) {
		// builder.append(cursor.getString(0)).append("#");
		// builder.append(cursor.getString(1)).append("#");
		// builder.append(cursor.getString(2)).append("#");
		// builder.append(cursor.getString(3)).append("#");
		// builder.append(cursor.getString(4)).append("#");
		// builder.append(cursor.getString(5)).append("\n");
		// }
		// txtTableContent.setText(builder);
		// }
		// cursor.close();
		// }
		// });
	}

	private String getProductName(String foodId) {
		Cursor cursor = foodDB.getProductNameFromFoodId(foodId);
		String productName = "";
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			productName = cursor.getString(0);
			txtProductName.setText(productName);
		}
		cursor.close();
		return productName;
	}

	private void getRatingValue(String foodId) {
		Cursor cursor = foodDB.getRatingFromFoodId(foodId);
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				int ratingValue = Integer.parseInt(cursor.getString(0));
				switch (ratingValue) {
				case 1:
					txtRatingValue.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.spis_mest));
					break;
				case 2:
					txtRatingValue.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.spis_mindre));
					break;
				case 3:
					txtRatingValue.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.spis_mindst));
					break;
				default:
					break;
				}
			}
		}
		cursor.close();
	}

	private void putProductInBasket(final String productName, final String foodId) {
//		final Dialog dialog = new Dialog(ProductInfoBasicActivity.this);
//		dialog.setContentView(R.layout.custom_dialog);
//		dialog.setTitle("           Læg i kurven           ");
//
//		final EditText edtQuantity = (EditText) dialog.findViewById(R.id.editQuantityNumber);
//		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinnerUnits);
//		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
//				ProductInfoBasicActivity.this, R.array.units_array,
//				android.R.layout.simple_spinner_item);
//		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		spinner.setAdapter(adapter);
//
//		Button btnAddToBasket = (Button) dialog.findViewById(R.id.btnAddToBasket);
//		btnAddToBasket.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				String date = DateHelper.getDate();
//				String unit = (String) spinner.getSelectedItem();
//				String quantity = edtQuantity.getText().toString();
//				Cursor cursor = foodDB.getProductName_id(foodId);
//				if (cursor.getCount() > 0) {
//					cursor.moveToFirst();
//					int primKeyId = cursor.getInt(0);
//					cursor.close();
//					if (!quantity.equals("")) {
//						if (ProductTabWidgetActivity.fromScan) {
//							foodDB.insertInBasket(primKeyId, quantity + " " + unit, date, null,
//									scanningsID);
//						} else {
//							foodDB.insertInBasket(primKeyId, quantity + " " + unit, date, recID,
//									null);
//						}
//						Toast.makeText(ProductInfoBasicActivity.this, "Tilføjet til kurven",
//								Toast.LENGTH_LONG).show();
//						dialog.dismiss();
//						startActivity(new Intent(ProductInfoBasicActivity.this,
//								BasketActivity.class));
//						//finish();
//					} else {
//						Toast.makeText(ProductInfoBasicActivity.this, "Indtast mængde",
//								Toast.LENGTH_LONG).show();
//					}
//				}
//			}
//		});
		
		Cursor cursor = foodDB.getProductName_id(foodId);
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            int primKeyId = cursor.getInt(0);
            cursor.close();
            
            if (ProductTabWidgetActivity.fromScan) {
                foodDB.insertInBasket(primKeyId, "0", date, null,
                        scanningsID);
            } else {
                foodDB.insertInBasket(primKeyId, "0", date, recID,
                        null);
            }
            Toast.makeText(ProductInfoBasicActivity.this, "Tilføjet til kurven",
                    Toast.LENGTH_LONG).show();
            startActivity(new Intent(ProductInfoBasicActivity.this,
                    BasketActivity.class));
        }
		//dialog.show();
	}

	private void setRecommendationType() {
		if (ProductTabWidgetActivity.fromScan) {
	    Cursor c = foodDB.getRatingFromFoodId(foodId);
    		if (c.getCount() > 0) {
    			c.moveToFirst();
    			if (Integer.parseInt(c.getString(0)) > 1) {
    				switch (new Random().nextInt(5)) {
    				case 0:
    				    standardRecommender();
    					break;
    				case 2:
    					seriousRecommender();
    					break;
    				case 4:
    					provocativeRecommender();
    					break;
    				default:
    					// do nothing
    					break;
    				}
    			}
    		}
    		c.close();
		}
	}

	private void seriousRecommender() {
		final Dialog dialog = new Dialog(ProductInfoBasicActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.recommend_dialog);
		
		TextView txtRunning = (TextView) dialog.findViewById(R.id.txtRunning);
		TextView txtSwimming = (TextView) dialog.findViewById(R.id.txtSwimming);
		TextView txtCycling = (TextView) dialog.findViewById(R.id.txtCycling);
		TextView txtSerious = (TextView) dialog.findViewById(R.id.seriousTxt);
		
		Cursor c = foodDB.getProductName_id(foodId);
        c.moveToFirst(); 
        int primKeyId = c.getInt(0);
        foodDB.insertInRecommended(primKeyId, null, scanningsID, 3, date);
        c.close();
		
		Cursor cursor = foodDB.getKiloJoule(foodId);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			double KJPERKCAL = 0.2390; // 1 kJ = 0,2390 kcal
			int running = 10; // 10 kcal/min
			int swimming = 13;  // 13 kcal/min
			int cycling = 11; // 11 kcal/min
			double kJ = Double.parseDouble(cursor.getString(1));
			double kcal = kJ * KJPERKCAL;
			int minutesRunning = (int) kcal / running;
			int minutesSwimming = (int) kcal / swimming;
			int minutesCycling = (int) kcal / cycling;
			
			switch(new Random().nextInt(3)) {
			case 0:
			    txtSerious.setText("For at forbrænde 100 g/ml af denne vare skal du løbe i " + minutesRunning + " minutter.");
			    break;
			case 1:
			    txtSerious.setText("For at forbrænde 100 g/ml af denne vare skal du svømme i " + minutesSwimming + " minutter.");
			    break;
			case 2:
			    txtSerious.setText("For at forbrænde 100 g/ml af denne vare skal du cykle i " + minutesCycling + " minutter.");
			    break;
		    default:
		        // WHUT?!!? something odd must have happened!
			    break;
			}

			txtRunning.setText(kcalToActivity(minutesRunning));
			txtSwimming.setText(kcalToActivity(minutesSwimming));
			txtCycling.setText(kcalToActivity(minutesCycling));
		}
		dialog.show();
	}
	
	private void standardRecommender() {
	    final Dialog dialog = new Dialog(ProductInfoBasicActivity.this); 
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.recommend);
        TextView txtEnergiValueDetailed = (TextView) dialog.findViewById(R.id.txtEnergiValueDetailed1);
        TextView txtProteinTotalValue = (TextView) dialog.findViewById(R.id.txtProteinTotalValue1);
        TextView txtFedtTotalValueDetailed = (TextView) dialog.findViewById(R.id.txtFedtTotalValueDetailed1);
        TextView txtKulhydratTotalValue = (TextView) dialog.findViewById(R.id.txtKulhydratTotalValue1);
        TextView productName = (TextView) dialog.findViewById(R.id.productName);
        Button selectProduct = (Button) dialog.findViewById(R.id.btnSelectProduct);
        ImageView productImg = (ImageView) dialog.findViewById(R.id.productDrawable);
        
        Cursor cursor = foodDB.getRecommendedProductsInCategory2(foodId);
        
        if (cursor.getCount() > 0) {
            cursor.moveToPosition(new Random().nextInt(cursor.getCount() - 1));
            productName.setText(cursor.getString(1));
            
            Cursor c = foodDB.getProductName_id(cursor.getString(0));
            c.moveToFirst(); 
            int primKeyId = c.getInt(0);
            foodDB.insertInRecommended(primKeyId, null, scanningsID, 2, date);
            c.close();
            
            switch (Integer.parseInt(cursor.getString(2))) {
            case 1:
                productImg.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.spis_mest));
                break;
            case 2:
                productImg.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.spis_mindre));
                break;
            case 3:
                productImg.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.spis_mindst));
                break;
            default:
                // Something went terribly wrong
                break;
            }
            
            final String tmpFoodId = cursor.getString(0);
            
            selectProduct.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent i = new Intent(getApplicationContext(), ProductTabWidgetActivity.class);
                    i.putExtra("foodId", tmpFoodId);
                    dialog.dismiss();
                    startActivity(i);
                }
            });
            
            cursor = foodDB.getDetailedNutrientsFromFoodId(tmpFoodId);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    int compId = Integer.parseInt(cursor.getString(0));
                    switch(compId) {
                    case 0:
                        // Might throw a NumberFormat Exception, but all BestLoc values
                        // for Energi are whole integer numbers
                        int energiValue = Integer.parseInt(cursor.getString(1));
                        int kcal = energiValue * 1000 / 4184;   // 1 kilocalorie = 4184 joules
                        txtEnergiValueDetailed.setText(energiValue + " kJ/" + kcal + " kcal");
                        break;
                    case 1:
                        txtProteinTotalValue.setText(cursor.getString(1) + " g");
                        break;
                    case 3:
                        txtFedtTotalValueDetailed.setText(cursor.getString(1) + " g");
                        break;
                    case 8:
                        txtKulhydratTotalValue.setText(cursor.getString(1) + " g");
                        break;
                    default:
                        break;
                    }
                }
            }
            cursor.close();
        } else {
            dialog.dismiss();
            return;
        }
        
        dialog.show();
    }
	
	private void provocativeRecommender() {
		final Dialog dialog = new Dialog(ProductInfoBasicActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.provorecommend_dialog);

		Cursor c = foodDB.getProductName_id(foodId);
        c.moveToFirst(); 
        int primKeyId = c.getInt(0);
        foodDB.insertInRecommended(primKeyId, null, scanningsID, 4, date);
        c.close();
		
        TextView txtProvoText = (TextView) dialog.findViewById(R.id.txtProvoText);
        ImageView imgFedme = (ImageView) dialog.findViewById(R.id.imgFedme);
		
		float[] values = checkforValues();
		
		if (values != null)
		{
			if (containsBigValue(values))
			{	
				switch (getBigFlag(values))
				{
				case 0:
					txtProvoText.setText("Denne vare indeholder meget fedt!\n\nOvervej at købe et fedtfattig alternativ.");
					
					switch (new Random().nextInt(3))
					{
					case 0:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					case 1:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.fedme));
						break;
					case 2:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbutt));
						break;
					default:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					}
					break;
				case 1:
					txtProvoText.setText("Der er meget sukker i denne vare. Har du overvejet at vælge en sukkerfri vare istedetfor?");

					switch (new Random().nextInt(2))
					{
					case 0:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.sugar));
						break;
					case 1:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.sugarskulls));
						break;
					default:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.sugar));
						break;
					}
					break;
				case 2:
					txtProvoText.setText("Kulhydratindholdet i denne vare er højt. Måske skulle du overveje en vare med færre kulhydrater");
					
					switch (new Random().nextInt(3))
					{
					case 0:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					case 1:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.fedme));
						break;
					case 2:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.carbo2));
						break;
					default:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					}
					break;
				case 3:
					txtProvoText.setText("Der er alkohol i denne vare. Måske skulle du tage en vare uden alkohol.");
					
					switch (new Random().nextInt(2))
					{
					case 0:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					case 1:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.fatalcoholic));
						break;
					default:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.bigbelly));
						break;
					}
				case 4:
					txtProvoText.setText("Der er et højt indhold af mættet fedt i denne vare.");
					
					switch (new Random().nextInt(2))
					{
					case 0:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.fatheart));
						break;
					case 1:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.cloggedartery));
						break;
					default:
						imgFedme.setBackgroundDrawable(getResources().getDrawable(R.drawable.fatheart));
						break;
					}
				break;
				}
				dialog.show();
			}
		}
	}
	
	private int getBigFlag(float[] values)
	{
		boolean found = false;
		int bigFlag = -1;
		
		while (!found)
		{
			bigFlag = new Random().nextInt(values.length-1);
			
			if (values[bigFlag] >= LOWEST_LIMIT)
				found = true;
		}
		
		return bigFlag;
	}
	
	private boolean containsBigValue(float[] values)
	{
		boolean a = false;
		for (int i = 0; i < values.length-1; i++)
			if (values[i] >= LOWEST_LIMIT)
				a = true;
		return a;
	}
	
	private float[] checkforValues() {
		float[] values = new float[5];
		
		Cursor cursor = foodDB.getDetailedNutrientsFromFoodId(foodId);
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				int compId = Integer.parseInt(cursor.getString(0));
			    
				switch(compId) {
			    case 0:
	                break;
			    case 1:
	                break;
			    case 2:
	                break;
			    case 3:
	                //Total fedt værdi
			    	float tal = Float.parseFloat(cursor.getString(1));
			    	values[0] =  (tal > FAT_LIMIT ? tal : -1.0f);
	                break;
			    case 4:
			    	//Mættede fedtsyrer
			    	float maetfedt = Float.parseFloat(cursor.getString(1));
			    	values[4] =  (maetfedt > SAT_FAT_LIMIT ? maetfedt : -1.0f);
	                break;
			    case 5:
	                break;
			    case 6:
	                break;
			    case 7:
	                break;
			    case 8:
			    	//Kulhydrater
			    	float kulhydrater = Float.parseFloat(cursor.getString(1));
			    	values[2] =  (kulhydrater > CARB_LIMIT ? kulhydrater : -1.0f);
	                break;
			    case 9:
			    	//Sukker
			    	float sukker = Float.parseFloat(cursor.getString(1));
			    	values[1] =  (sukker > SUGAR_LIMIT ? sukker : -1.0f);
	                break;
			    case 10:
	                break;
			    case 11:
			    	//Alkohol
			    	float alkohol = Float.parseFloat(cursor.getString(1));
			    	values[3] =  (alkohol > ALCOHOL_LIMIT ? alkohol : -1.0f);
	                break;
			    case 12:
	                break;
			    case 13:
	                break;
			    default:
	                throw new Error("Fejl 40!");
			    }
			}
		}
		cursor.close();
				
		return values;
	}
	
	private String kcalToActivity(int minut) {
		String time;
		if (minut < 1.0) {
			time = String.valueOf(minut * 60) + " sekunder";
		} else {
			time = String.valueOf(minut) + " minutter";
		}
		return time;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.product_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent i;
		switch (item.getItemId()) {
		case R.id.menu_item_scan:
			startBarcodeScanner();
			return true;
		case R.id.menu_item_home:
			i = new Intent(getApplicationContext(), HomescreenActivity.class);
			startActivity(i);
			return true;
		case R.id.menu_item_shoppingBasket:
			i = new Intent(getApplicationContext(), BasketActivity.class);
			startActivity(i);
			return true;
		case R.id.menu_item_settings:
			i = new Intent(getApplicationContext(), UserInfoActivity.class);
			startActivity(i);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void startBarcodeScanner() {
		Intent i = new Intent(getApplicationContext(), CaptureActivity.class);
		startActivity(i);
	}
}
